<?php
/**
 * Created by JetBrains PhpStorm.
 * User: P2DC
 * Date: 25/7/2556
 * Time: 10:23 น.
 * To change this template use File | Settings | File Templates.
 */

class Cron
{
    static private $_instance = null;

    /**
     * @return Cron
     */
    static public function instance()
    {
        if(static::$_instance == null){
            static::$_instance = new static();
        }
        $instance = static::$_instance;
        return $instance;
    }


    private function searchArr($arr, $attr, $search)
    {
        foreach($arr as $key => $item){
            if($item[$attr]==$search)
                return $item;
        }
        return null;
    }

    private $_price = null; // price = $_price[packageId][month];
    private function findPrice($packageId, $month)
    {
        if($this->_price==null){
            $prices = Price::instance()->get();
            $this->_price = array();
            foreach($prices as $key => $price){
                if(!isset($this->_price[$price['packageId']])){
                    $this->_price[$price['packageId']] = array();
                }
                $this->_price[$price['packageId']][$month] = $price['price'];
            }
        }
        if(isset($this->_price[$packageId][$month])){
            return $this->_price[$packageId][$month];
        }
        else {
            var_dump($this->_price[$packageId]);
            $this->_price[$packageId][1]*$month;
        }
    }

    public function actionProductStatus()
    {
        $pdo = Db::getPDO();
        $st = $pdo->query("
            SELECT * FROM Product
                WHERE NOW() >= DATE_SUB(DATE(dateTimeout),INTERVAL 7 DAY)
                AND NOW() < DATE(dateTimeout)
                AND id NOT IN
                    (
                        SELECT productId FROM Invoice
                        WHERE isNew=0
                        AND DATE(createTime) >= DATE_SUB(NOW(),INTERVAL 7 DAY)
                        AND DATE(createTime) < NOW()
                    )
            ");
        $products = $st->fetchAll(PDO::FETCH_ASSOC);
        $coloId = array();
        $vpsId = array();
        $hostingId = array();

        foreach($products as $key => $product){
            if($product['type']=='colo')
                $coloId[] = $product['id'];
            else if($product['type']=='vps')
                $vpsId[] = $product['id'];
            else if($product['type']=='hosting')
                $hostingId[] = $product['id'];
        }

        if(count($coloId)>0){
            $productsColo = ProductColo::instance()->get(array('id'=>$coloId));
            foreach($products as $key => $product){
                if($product['type']=='colo'){
                    $products[$key] = array_merge($product, $this->searchArr($productsColo, 'id', $product['id']));
                }
            }
        }
        else if(count($vpsId)>0){
            $productsVPS = ProductVPS::instance()->get(array('id'=> $vpsId));
            foreach($products as $key => $product){
                if($product['type']=='vps'){
                    $products[$key] = array_merge($product, $this->searchArr($productsVPS, 'id', $product['id']));
                }
            }
        }
        else if(count($hostingId)>0){
            $productsHosting = ProductVPS::instance()->get(array('id'=>$hostingId));
            foreach($products as $key => $product){
                if($product['type']=='vps'){
                    $products[$key] = array_merge($product, $this->searchArr($productsHosting, 'id', $product['id']));
                }
            }
        }

        $this->actionCreateInvoice($products);
    }

    public function actionCreateInvoice(array $products = array())
    {
        if(count($products)==0){
            return;
        }
        $pdo = Db::getPDO();
        try {
            Table::instanceTable('Package')->joinTo('package', 'id', 'packageId', $products, Table::JOIN_ONE);
            Table::instanceTable('Account')->joinTo('account', 'id', 'accountId', $products, Table::JOIN_ONE);

            foreach($products as $key => $product){
                $pdo->beginTransaction();
                try {
                    Invoice::instance()->add(array(
                        'type'=> $product['type'],
                        'packageId'=> $product['packageId'],
                        'price'=> $this->findPrice($product['packageId'], $product['month']),
                        'month'=> $product['month'],
                        'profileType'=> $product['profileType'],
                        'profileId'=> $product['profileId'],
                        'accountId'=> $product['accountId'],
                        'dateDue'=> $product['dateTimeout'],
                        'info'=> $product['package']['info'],
                        'isNew'=> 0,
                        'status'=> 0,
                        'productId'=> $product['id'],
                    ));
                    $id = $pdo->lastInsertId();
                    if($product['type']=='colo'){
                        InvoiceColo::instance()->add(array(
                            'id'=> $id,
                            'ipNum'=> 0,
                            'net'=> 0,
                            'admin'=> 0
                        ));
                    }
                    else if($product['type']=='vps'){
                        InvoiceVPS::instance()->add(array(
                            'id'=> $id,
                            'os'=> $product['os']
                        ));
                    }
                    else if($product['type']=='hosting'){
                        InvoiceHosting::instance()->add(array(
                            'id'=> $id,
                            'serverName'=> $product['serverName'],
                            'domain'=> $product['domain']
                        ));
                    }
                    $pdo->commit();
                }
                catch(Exception $e) {
                    $pdo->rollBack();
                    throw $e;
                }
            }
        }
        catch(Exception $e) {
            Log::cron($e);
            throw $e;
        }
    }

    public function actionInvoiceTimeout(array $invoices = array())
    {

    }
}